﻿Imports System.Drawing

Public Class AquariumDetail
    Inherits ItemDetailPage

    Protected Property PhotoNormalSize() As New Size() With {.width = 512, .height = 256}
    Protected Property PhotoThumbSize() As New Size() With {.width = 128, .height = 64}
    Protected Property AquariumID() As ULong

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AquariumID = CULng(Request.QueryString.Get("ID"))
        If Not IsPostBack Then
            If Not AquariumID AndAlso Request.QueryString.Get("Action") = "Add" Then
                If InsertionPermitted Then
                    DetailFormView.DefaultMode = FormViewMode.Insert
                    UpdateProductList()
                Else
                    StopEditing()
                End If
            ElseIf AquariumID AndAlso AquariumExists(AquariumID) Then
                If Request.QueryString.Get("Action") = "Edit" Then
                    If ModificationPermitted Then
                        DetailFormView.DefaultMode = FormViewMode.Edit
                        UpdateDataSource()
                        UpdateProductList(AquariumID)
                    Else
                        StopEditing()
                    End If
                Else
                    DetailFormView.DefaultMode = FormViewMode.ReadOnly
                    UpdateDataSource()
                End If
            Else
                RedirectToList()
            End If
        End If
    End Sub

    Protected Sub SaveButton_Click(sender As Object, e As EventArgs)
        If ModificationPermitted Then
            Dim gateway As New AquariumGateway()
            Dim title As TextBox = DetailFormView.FindControl("TitleTextBox")
            Dim description As TextBox = DetailFormView.FindControl("DescriptionTextBox")
            Dim type As DropDownList = DetailFormView.FindControl("AquariumTypeList")
            Dim waterTemp As TextBox = DetailFormView.FindControl("WaterTempTextBox")
            Dim product As DropDownList = DetailFormView.FindControl("ProductList")
            Dim lastCleaned As TextBox = DetailFormView.FindControl("LastCleanedTextBox")
            Dim cleanPeriod As TextBox = DetailFormView.FindControl("CleanPeriodTextBox")
            Dim tag As TextBox = DetailFormView.FindControl("TagTextBox")
            Dim photo As FileUpload = DetailFormView.FindControl("PhotoFileUpload")
            Dim photoID As ULong
            If photo.HasFile() Then
                Dim fileName As String = PhotoUtils.GetUniqueFileName(photo.FileName)
                PhotoUtils.Save(fileName, photo.PostedFile.InputStream, PhotoNormalSize, PhotoThumbSize)
                photoID = CreatePhoto(title.Text, description.Text, fileName)
            Else
                photoID = 1 ' The database has one default photo for aquariums
            End If
            gateway.Update(AquariumID, title.Text, description.Text, type.Text,
                           CDate(lastCleaned.Text), CInt(cleanPeriod.Text),
                           CDbl(waterTemp.Text), CULng(product.SelectedValue),
                           photoID)
            UpdateTags()
            StopEditing()
        End If
    End Sub

    Protected Sub CancelEditButton_Click(sender As Object, e As EventArgs)
        StopEditing()
    End Sub

    Protected Sub EditButton_Click(sender As Object, e As EventArgs)
        StartEditing()
    End Sub

    Protected Sub DeleteButton_Click(sender As Object, e As EventArgs)
        If ModificationPermitted Then
            Dim gateway As New AquariumGateway()
            gateway.DeleteByID(AquariumID)
            RedirectToList()
        End If
    End Sub

    Protected Sub SubmitButton_Click(sender As Object, e As EventArgs)
        If InsertionPermitted Then
            Dim gateway As New AquariumGateway()
            Dim title As TextBox = DetailFormView.FindControl("TitleTextBox")
            Dim description As TextBox = DetailFormView.FindControl("DescriptionTextBox")
            Dim type As DropDownList = DetailFormView.FindControl("AquariumTypeList")
            Dim waterTemp As TextBox = DetailFormView.FindControl("WaterTempTextBox")
            Dim product As DropDownList = DetailFormView.FindControl("ProductList")
            Dim lastCleaned As TextBox = DetailFormView.FindControl("LastCleanedTextBox")
            Dim cleanPeriod As TextBox = DetailFormView.FindControl("CleanPeriodTextBox")
            Dim tag As TextBox = DetailFormView.FindControl("TagTextBox")
            Dim photo As FileUpload = DetailFormView.FindControl("PhotoFileUpload")
            Dim photoID As ULong
            If photo.HasFile() Then
                Dim fileName As String = PhotoUtils.GetUniqueFileName(photo.FileName)
                PhotoUtils.Save(fileName, photo.PostedFile.InputStream, PhotoNormalSize, PhotoThumbSize)
                photoID = CreatePhoto(title.Text, description.Text, fileName)
            Else
                photoID = 1 ' The database has one default photo for aquariums
            End If
            AquariumID = gateway.Insert(title.Text, description.Text, type.Text,
                                        CDate(lastCleaned.Text), CInt(cleanPeriod.Text),
                                        CDbl(waterTemp.Text), CULng(product.SelectedValue),
                                        GetCurrentUserID(), photoID)
            UpdateTags()
            StopEditing()
        End If
    End Sub

    Protected Sub SubmitCommentButton_Click(sender As Object, e As EventArgs)
        If InsertionPermitted Then
            Dim gateway As New CommentGateway()
            Dim commentTitle As TextBox = DetailFormView.FindControl("CommentTitleTextBox")
            Dim commentBody As TextBox = DetailFormView.FindControl("CommentBodyTextBox")
            gateway.Insert(AquariumID, commentTitle.Text, commentBody.Text, GetCurrentUserID())
            StopEditing()
        End If
    End Sub

    Protected Sub UpdateTags()
        Dim tagGateway As New AquariumTagGateway()
        Dim tags As TextBox = DetailFormView.FindControl("TagTextBox")
        tagGateway.Update(AquariumID, New ArrayList(tags.Text.Split(",")), GetCurrentUserID())
    End Sub

    Protected Function AquariumExists(ByVal ID As ULong) As Boolean
        Dim gateway As New AquariumGateway()
        Return gateway.Exists(ID)
    End Function

    Protected Overrides ReadOnly Property UserHasOwnership() As Boolean
        Get
            Dim gateway As New AquariumGateway()
            Return gateway.HasOwnership(AquariumID, User.Identity.Name)
        End Get
    End Property

    Protected Sub StartEditing()
        Dim redirectUrl As String = String.Format("~/Pages/AquariumDetail.aspx?ID={0}&Action=Edit", AquariumID)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub StopEditing()
        Dim redirectUrl As String = String.Format("~/Pages/AquariumDetail.aspx?ID={0}", AquariumID)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub RedirectToList()
        Dim redirectUrl As String = String.Format("~/Pages/AquariumList.aspx")
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub UpdateDataSource()
        Dim aquariumGateway As New AquariumGateway()
        DetailFormView.DataSource = aquariumGateway.FindByID(AquariumID)
        DetailFormView.DataBind()

        Dim nestedView As ListView = DetailFormView.FindControl("NestedDetailListView")
        If nestedView IsNot Nothing Then
            Dim commentGateway As New CommentGateway()
            nestedView.DataSource = commentGateway.FindByID(AquariumID)
            nestedView.DataBind()
        End If
    End Sub

    Protected Sub UpdateProductList(Optional ByVal aquariumID As ULong = 0)
        ' This is visible in Add/Edit views
        Dim productList As DropDownList = DetailFormView.FindControl("ProductList")
        If productList IsNot Nothing Then
            Dim productGateway As New ProductGateway()
            productList.DataSource = productGateway.FindAll()
            If aquariumID <> 0 Then
                Dim aquariumGateway As New AquariumGateway()
                productList.SelectedValue = aquariumGateway.FindByID(aquariumID)(0)("ProductID")
            End If
            productList.DataBind()
        End If
    End Sub

    Protected Function GetAquariumTagsCSV(ByVal aquariumID As ULong) As String
        Dim gateway As New AquariumTagGateway()
        Dim tags As ArrayList = gateway.GetAquariumTagsList(aquariumID)
        Return Join(tags.ToArray(), ", ")
    End Function

    Protected Function GetAquariumTags(ByVal aquariumID As ULong) As DataTable
        Dim gateway As New AquariumTagGateway()
        Return gateway.FindAquariumTags(aquariumID)
    End Function

    Protected Sub TagEditLinkButton_Click(sender As Object, e As EventArgs)
        DetailFormView.FindControl("TagRepeater").Visible = False
        DetailFormView.FindControl("TagEditLinkButton").Visible = False
        DetailFormView.FindControl("TagTextBox").Visible = True
        DetailFormView.FindControl("TagSaveLinkButton").Visible = True
        DetailFormView.FindControl("TagEditCancelLinkButton").Visible = True
    End Sub

    Protected Sub TagSaveLinkButton_Click(sender As Object, e As EventArgs)
        If InsertionPermitted Then
            UpdateTags()
            StopEditing()
        End If
    End Sub

    Protected Sub TagEditCancelLinkButton_Click(sender As Object, e As EventArgs)
        StopEditing()
    End Sub

    Private Function CreatePhoto(ByVal title As String, ByVal description As String, ByVal filename As String) As ULong
        Dim gateway As New PhotoGateway()
        Return gateway.Insert(title, description, GetCurrentUserID(), filename)
    End Function

    Protected Function GetAquariumFish(ByVal aquariumID As ULong) As DataTable
        Dim gateway As New AquariumFishGateway()
        Return gateway.FindByID(aquariumID)
    End Function


    Protected Sub ThumbsUpImageButton_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
        If InsertionPermitted Then
            Dim gateway As New AquariumLikingGateway()
            gateway.InsertOrUpdate(AquariumID, GetCurrentUserID(), True)
            UpdateDataSource()
        End If
    End Sub

    Protected Sub ThumbsDownImageButton_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
        If InsertionPermitted Then
            Dim gateway As New AquariumLikingGateway()
            gateway.InsertOrUpdate(AquariumID, GetCurrentUserID(), False)
            StopEditing()
            UpdateDataSource()
        End If
    End Sub
End Class